package com.wyg.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.wyg.bean.User;
import com.wyg.service.LoginBiz;

/**
 * Servlet implementation class LoginServlet
 */
@WebServlet("/Login")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginServlet() {
        super();
        System.out.println("LoginServlet");
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		System.out.println("---");
		response.setContentType("text/html");
		
		LoginBiz loginBiz = new LoginBiz();
		User user = new User();
		String userName = request.getParameter("userName");
		String userPassword = request.getParameter("userPassword");
		user.setUserName(userName);
		user.setUserPassword(userPassword);
		
		boolean result = loginBiz.validateUser(user);
		String rememberPassword = request.getParameter("rememberPassword");
		if (result) {
			request.getSession().setAttribute("user", user);
			
			if (rememberPassword != null) {
				Cookie nameCookie = new Cookie("userName", userName);
				Cookie passwordCookie = new Cookie("userPassword", userPassword);
				nameCookie.setMaxAge(30 * 60);
				passwordCookie.setMaxAge(30 * 60);
				response.addCookie(nameCookie);
				response.addCookie(passwordCookie);
			}
			response.sendRedirect("view/servlet");
		} else {
			response.sendRedirect("login.jsp");
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
